package com.zhugang.week07;

import java.util.PriorityQueue;

/**
 * @program algorithms
 * @description: mergeKList
 * @author: chanzhugang
 * @create: 2022/08/02 08:56
 */
public class MergeKLists2 {

    /**
     * 23 合并K个升序链表
     *
     * @param lists
     * @return
     */
    public ListNode mergeKList(ListNode[] lists) {
        // 小顶堆 + 链表尾插法
        if (lists == null || lists.length == 0) {
            return null;
        }
        PriorityQueue<ListNode> minQueue = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
        for (ListNode node : lists) {
            if (node != null) {
                minQueue.offer(node);
            }
        }
        ListNode newHead = new ListNode();
        ListNode tail = newHead;
        while (!minQueue.isEmpty()) {
            ListNode curNode = minQueue.poll();
            tail.next = curNode;
            tail = tail.next;
            if (curNode.next != null) {
                minQueue.offer(curNode.next);
            }
        }
        return newHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}